package com.xmy.study.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.MessageFormat;
import java.util.UUID;

/**
 * 图片工具类
 *
 * @author HeLin
 */
@Component
public class ImagesUtil {

    /**
     * 总路径（保存路径+文件名称）
     */
    public String imgFilePath;

    /**
     * 文件保存路径
     */
    public String pathFile;

    /**
     * 图片上传
     *
     * @param base64Data
     * @return
     * @throws IOException
     */
    public ResponseEntity<JSONObject> uploadImageBase(@RequestParam(value = "img") String base64Data) throws IOException {
        //新建文件夹
        File folder = new File(pathFile);
        if (!folder.exists() && !folder.isDirectory()) {
            folder.setWritable(true, false);
            folder.mkdirs();
        }

        JSONObject json = new JSONObject();
        String dataPrix = "";
        String data = "";
        if (base64Data == null || "".equals(base64Data)) {
            json.put("STATUS", "ERROR");
            json.put("MSG", "上传失败，上传图片数据为空");
            return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST);
        } else {
            String[] d = base64Data.split("base64,");
            if (d != null) {
                dataPrix = d[0];
                data = d[1];
            } else {
                json.put("STATUS", "ERROR");
                json.put("MSG", "上传失败，数据不合法");
                return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST);
            }
        }
        String suffix = "";
        if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
            suffix = ".jpg";
        } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
            suffix = ".ico";
        } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
            suffix = ".gif";
        } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
            suffix = ".png";
        } else {
            json.put("STATUS", "ERROR");
            json.put("MSG", "上传图片格式不合法");
            return new ResponseEntity<>(json, HttpStatus.BAD_REQUEST);
        }
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String tempFileName = uuid + suffix;

        imgFilePath = pathFile + tempFileName;

        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            byte[] b = decoder.decodeBuffer(data);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            json.put("STATUS", "200");
            json.put("MSG", "上传图片成功");
            return new ResponseEntity<>(json, HttpStatus.OK);
        } catch (IOException e) {
            json.put("STATUS", "ERROR");
            json.put("MSG", "系统异常，上传图片失败");
            return new ResponseEntity<>(json, HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            out.close();
        }
    }

    /**
     * 删除原来的文件
     *
     * @param name
     */
    public void delete(String name) {
        try {
            //路径
            File folder = new File(pathFile);
            File[] files = folder.listFiles();
            for (File file : files) {
                //文件图片名
                if (file.getName().equals(name)) {
                    file.delete();
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 查询图片并以base64格式返回
     *
     * @param imgPath
     * @return
     */
    public String doGetImageStrFromPath(String imgPath) {
        InputStream in = null;
        byte[] data = null;
        // 读取图片字节数组
        try {
            in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
        } catch (IOException e) {
            e.printStackTrace();
            String exMsg = MessageFormat.format("通过图片文件路径获取Base64字符串时发生异常：{0}", e.getMessage());
            return exMsg;
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                String exMsg = MessageFormat.format("通过图片URL获取Base64字符串关闭InputStream时发生异常：{0}", e.getMessage());
                return exMsg;
            }
        }
        // 对字节数组Base64编码
        byte[] encodeBase64 = Base64.encodeBase64(data);
        // 返回Base64编码过的字节数组字符串
        String imageBase64String = new String(encodeBase64);
        if (null == imageBase64String || imageBase64String.length() == 0) {
            return "图片Base64字符串为空,请检查造成原因";
        }
        imageBase64String = "data:image/png;base64," + imageBase64String;
        imageBase64String = imageBase64String.substring(0, imageBase64String.length() - 1);
        return imageBase64String;
    }


}
